layui.define(['upload','layer'], function(exports) {
    "use strict";

    var $=layui.jquery;

    /**
     * @constructor newTable 构造函数
     */
    var NewUpload = function() {
    	this.target=layui.upload;
        this.layer=layui.layer
        this.config={
            elem:undefined
            ,url:undefined
            ,size:1024*2
        }
    };

    NewUpload.prototype.render=function (option) {
        var that = this;
        $.extend(true, that.config, option);
        return that;
    }
    
    NewUpload.prototype.bindUpload=function (isMulti,success) {
        isMulti = (typeof(isMulti) === "undefined") ? false : isMulti;
        var that = this;

        //绑定删除事件,先解绑。
        $('div.layui-upload-list').off().on('click','span.close',function (e) {
            var input = $(this).parent().parent().prev().prev().prev();

            var imgSrcs=input.val().split(",");

            imgSrcs.splice(($(this).parent().index()),1);

            input.val(imgSrcs.join(","));

            $(this).parent().remove();
        });

        $(that.config.elem).each(function (index) {
            var button=this;
            var nextDiv=$(button).next();
            var nextChildren=nextDiv.children();
            var uploadInst = that.target.render({
                elem: 'button[name='+button.name+']'
                ,url: that.config.url
                ,size: that.config.size //限制文件大小，单位 KB
                ,multiple:isMulti
                ,before: function(obj){
                    layui.layer.load();
                    if(isMulti){
                            //预读本地文件示例，不支持ie8
                        obj.preview(function(index, file, result){
                            nextDiv.append('<div class="imgItem"><img class="layui-upload-img" style="width: 200px;" src="'+result+'"><span class="close">X</span></div>') //图片链接（base64）
                        })
                    }else{
                        //预读本地文件示例，不支持ie8
                        obj.preview(function(index, file, result){
                            nextChildren.find('img').attr('src', result); //图片链接（base64）
                        });
                    }

                }
                ,done: function(res){
                    layui.layer.closeAll('loading');
                    //如果上传失败
                    if(res.code > 0){
                        //演示失败状态，并实现重传
                        var demoText = nextChildren.eq(1);
                        demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
                        demoText.find('.demo-reload').on('click', function(){
                            uploadInst.upload();
                        });
                        return that.layer.msg('上传失败');
                    }else {
                        var inputVal=$('button[name='+button.name+']').prev();
                        if(isMulti){
                            if(inputVal.val()){
                                inputVal.val( inputVal.val() + (','+res.data));
                            }else{
                                inputVal.val(res.data)
                            }
                        }else {
                            inputVal.val(res.data);
                        }
                        if(success){
                            success(res.data);
                        }
                    }
                    //上传成功
                }
                ,error: function(){
                    //演示失败状态，并实现重传
                    var demoText = nextChildren.eq(1);
                    demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
                    demoText.find('.demo-reload').on('click', function(){
                        uploadInst.upload();
                    });
                }
            });
        })

        return that;
    }


    var newUpload=new NewUpload();

    exports('newUpload', newUpload);
});